/*
 * Copyright 2011 Philippe Blanc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package me.l1k3.fx.client.impl;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;

import me.l1k3.core.client.Core;
import me.l1k3.core.client.queue.Queue;
import me.l1k3.fx.client.event.FXEvent;
import me.l1k3.fx.client.event.FXEventHandler;
import me.l1k3.fx.client.inter.FX;

public abstract class FXBase implements FX, Queue {
    private EventBus bus;
    private Command callback;

    @Override
    public final EventBus getEventBus() {
        return bus;
    }

    @Override
    public final FX setEventBus(EventBus bus) throws Core.EventBusNoNullException {
        if(this.bus!=null) {
            throw new Core.EventBusNoNullException();
        }
        this.bus = bus;
        
        return this;
    }
    
    public final HandlerRegistration addFXEventHandler(FXEventHandler handler) {
        if(bus==null) {
            bus = Core.getEventBus();
        }
        
        return bus.addHandlerToSource(FXEvent.TYPE, this, handler);
    }
    
    protected void onStart() {
        if(bus!=null) {
            bus.fireEventFromSource(FXEvent.onStart(this), this);
        }
    }
 
    protected void onComplete() {
        if(bus!=null) {
            bus.fireEventFromSource(FXEvent.onComplete(this), this);
        }
        
        if(callback!=null) {
            Scheduler.get().scheduleDeferred(callback);
        }
    }
    
    @Override
    public void callback(Command callback) {
        this.callback = callback;
    }
}